package com.shangguan.spring.controller;

import com.google.gson.Gson;
import com.shangguan.spring.beans.User;
import com.shangguan.spring.common.ResultCommon;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ConcurrentAccessException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName: LoginController
 * @Description:
 * @Author: 一尘
 * @Date: 2020 年 05 月 19 14:15
 * @Version 1.0
 */
@RestController
@Slf4j
public class LoginController {

    @PostMapping("/login")
    public String login(@RequestBody User user){
          log.info("------------"+user.getUsername()+"-----------"+user.getUserpassword());
        UsernamePasswordToken  token = new UsernamePasswordToken(user.getUsername(),user.getUserpassword());
        Subject currentUser = SecurityUtils.getSubject();
        ResultCommon  result = new ResultCommon();
        try {
            currentUser.login(token);
            result.setSuccess(true);
            result.setMessage("登录成功!");
            currentUser.getSession().setAttribute("user",user);
        }
        catch (UnknownAccountException e) {
            result.setSuccess(false);
            result.setMessage("账号不存在!");
        }
        catch (IncorrectCredentialsException e) {
            result.setSuccess(false);
            result.setMessage("密码不正确!");
        }
        catch (LockedAccountException e) {
            result.setSuccess(false);
            result.setMessage("账户被锁定!");
        }
        catch (ConcurrentAccessException e) {
            result.setSuccess(false);
            result.setMessage("已经登录了!");
        }catch (AuthenticationException e) {
            result.setSuccess(false);
            result.setMessage("网络出错稍后再试!");
        }
        log.info("----"+result);
        Gson gson = new Gson();
        String s = gson.toJson(result);
        return  s;
    }



}
